package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {

	c1, c2 := generator(), generator()
	w := createWorker(0)
	//非阻塞获取
	//hasValue := false
	var values []int
	//十秒钟后退出
	tm := time.After(10 * time.Second)
	//定时器功能
	tick := time.Tick(time.Second * 2)
	for {
		var activeWorker chan<- int
		var activeValue int
		if len(values) > 0 {
			activeWorker = w
			activeValue = values[0]
		}
		select {
		case n := <-c1:
			//hasValue = true
			values = append(values, n)
		case n := <-c2:
			//hasValue = true
			values = append(values, n)
		case activeWorker <- activeValue: //nil channel会阻塞
			values = values[1:]
		case <-tm:
			fmt.Println("bye", values)
		case <-time.After(800 * time.Millisecond):
			fmt.Println("timeout")
		case <-tick:
			if len(values) > 10 {
				fmt.Println("消费太慢了")
			}

			//default:
			//	fmt.Println("no value received")
		}
	}

}

type Worker struct {
	in   chan int
	done chan bool
}

func worker(id int, c chan int) {
	for n := range c {
		time.Sleep(time.Second * 1)
		fmt.Printf("Worker %d received %d \n", id, n)
	}
}

func createWorker(id int) chan<- int {
	c := make(chan int)
	go worker(id, c)
	return c
}

func generator() chan int {
	out := make(chan int)
	go func() {
		i := 0
		for {
			time.Sleep(time.Duration(rand.Intn(1500)) * time.Millisecond)
			out <- i
			i++
		}
	}()
	return out
}
